const express = require('express');
const router = express.Router();
const db = require('../config/db');
const authenticateToken = require('../middleware/auth');

/**
 * @route   GET /api/memos
 * @desc    获取用户的所有备忘录
 * @access  Private
 */
router.get('/', authenticateToken, async (req, res) => {
  try {
    const { userId } = req.user;
    const { completed, priority } = req.query;

    let sql = 'SELECT * FROM memos WHERE user_id = ? AND is_deleted = 0';
    const params = [userId];

    // 根据完成状态过滤
    if (completed !== undefined) {
      sql += ' AND completed = ?';
      params.push(completed === 'true' ? 1 : 0);
    }

    // 根据优先级过滤
    if (priority) {
      sql += ' AND priority = ?';
      params.push(priority);
    }

    // 排序：未完成的在前，然后按优先级，最后按时间
    sql += ' ORDER BY completed ASC, FIELD(priority, "high", "medium", "low"), remind_time ASC';

    const [memos] = await db.query(sql, params);

    res.json({
      code: 200,
      message: '获取成功',
      data: memos
    });
  } catch (error) {
    console.error('获取备忘录错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      error: error.message
    });
  }
});

/**
 * @route   GET /api/memos/:id
 * @desc    获取单个备忘录详情
 * @access  Private
 */
router.get('/:id', authenticateToken, async (req, res) => {
  try {
    const { userId } = req.user;
    const { id } = req.params;

    const [memos] = await db.query(
      'SELECT * FROM memos WHERE id = ? AND user_id = ? AND is_deleted = 0',
      [id, userId]
    );

    if (memos.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '备忘录不存在'
      });
    }

    res.json({
      code: 200,
      message: '获取成功',
      data: memos[0]
    });
  } catch (error) {
    console.error('获取备忘录详情错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      error: error.message
    });
  }
});

/**
 * @route   POST /api/memos
 * @desc    创建新备忘录
 * @access  Private
 */
router.post('/', authenticateToken, async (req, res) => {
  try {
    const { userId } = req.user;
    const { content, priority = 'medium', remindTime } = req.body;

    // 验证输入
    if (!content || !content.trim()) {
      return res.status(400).json({
        code: 400,
        message: '内容不能为空'
      });
    }

    if (!remindTime) {
      return res.status(400).json({
        code: 400,
        message: '请选择提醒时间'
      });
    }

    // 验证优先级
    const validPriorities = ['low', 'medium', 'high'];
    if (!validPriorities.includes(priority)) {
      return res.status(400).json({
        code: 400,
        message: '无效的优先级'
      });
    }

    // 插入备忘录
    const [result] = await db.query(
      'INSERT INTO memos (user_id, content, priority, remind_time) VALUES (?, ?, ?, ?)',
      [userId, content, priority, remindTime]
    );

    // 获取新创建的备忘录
    const [newMemo] = await db.query(
      'SELECT * FROM memos WHERE id = ?',
      [result.insertId]
    );

    res.status(201).json({
      code: 200,
      message: '创建成功',
      data: newMemo[0]
    });
  } catch (error) {
    console.error('创建备忘录错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      error: error.message
    });
  }
});

/**
 * @route   PUT /api/memos/:id
 * @desc    更新备忘录
 * @access  Private
 */
router.put('/:id', authenticateToken, async (req, res) => {
  try {
    const { userId } = req.user;
    const { id } = req.params;
    const { content, priority, remindTime, completed } = req.body;

    // 检查备忘录是否存在且属于该用户
    const [existingMemos] = await db.query(
      'SELECT id FROM memos WHERE id = ? AND user_id = ? AND is_deleted = 0',
      [id, userId]
    );

    if (existingMemos.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '备忘录不存在'
      });
    }

    // 构建更新语句
    const updates = [];
    const params = [];

    if (content !== undefined) {
      if (!content.trim()) {
        return res.status(400).json({
          code: 400,
          message: '内容不能为空'
        });
      }
      updates.push('content = ?');
      params.push(content);
    }

    if (priority !== undefined) {
      const validPriorities = ['low', 'medium', 'high'];
      if (!validPriorities.includes(priority)) {
        return res.status(400).json({
          code: 400,
          message: '无效的优先级'
        });
      }
      updates.push('priority = ?');
      params.push(priority);
    }

    if (remindTime !== undefined) {
      updates.push('remind_time = ?');
      params.push(remindTime);
    }

    if (completed !== undefined) {
      updates.push('completed = ?');
      params.push(completed ? 1 : 0);
      
      if (completed) {
        updates.push('completed_at = NOW()');
      } else {
        updates.push('completed_at = NULL');
      }
    }

    if (updates.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '没有要更新的内容'
      });
    }

    params.push(id, userId);
    const sql = `UPDATE memos SET ${updates.join(', ')} WHERE id = ? AND user_id = ?`;
    
    await db.query(sql, params);

    // 获取更新后的备忘录
    const [updatedMemo] = await db.query(
      'SELECT * FROM memos WHERE id = ?',
      [id]
    );

    res.json({
      code: 200,
      message: '更新成功',
      data: updatedMemo[0]
    });
  } catch (error) {
    console.error('更新备忘录错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      error: error.message
    });
  }
});

/**
 * @route   PATCH /api/memos/:id/complete
 * @desc    标记备忘录为完成
 * @access  Private
 */
router.patch('/:id/complete', authenticateToken, async (req, res) => {
  try {
    const { userId } = req.user;
    const { id } = req.params;

    const [result] = await db.query(
      'UPDATE memos SET completed = 1, completed_at = NOW() WHERE id = ? AND user_id = ? AND is_deleted = 0',
      [id, userId]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({
        code: 404,
        message: '备忘录不存在'
      });
    }

    const [updatedMemo] = await db.query(
      'SELECT * FROM memos WHERE id = ?',
      [id]
    );

    res.json({
      code: 200,
      message: '已标记为完成',
      data: updatedMemo[0]
    });
  } catch (error) {
    console.error('完成备忘录错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      error: error.message
    });
  }
});

/**
 * @route   DELETE /api/memos/:id
 * @desc    删除备忘录（软删除）
 * @access  Private
 */
router.delete('/:id', authenticateToken, async (req, res) => {
  try {
    const { userId } = req.user;
    const { id } = req.params;

    const [result] = await db.query(
      'UPDATE memos SET is_deleted = 1, deleted_at = NOW() WHERE id = ? AND user_id = ? AND is_deleted = 0',
      [id, userId]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({
        code: 404,
        message: '备忘录不存在'
      });
    }

    res.json({
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    console.error('删除备忘录错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      error: error.message
    });
  }
});

module.exports = router;
